<template>
    <div class="http-container">
        <div class="content-wrapper">
            <!-- 左侧历史记录列表 -->
            <div class="history-section" :class="{ collapsed: isCollapsed }">
                <div class="history-header" @click="toggleCollapse">
                    <span class="collapse-icon" :class="{ collapsed: isCollapsed }">
                        ◀
                    </span>
                </div>
                <n-scrollbar class="history-list" v-show="!isCollapsed">
                    <div v-for="item in historyRequests" :key="item.id" class="history-item"
                        :class="{ active: selectedHistoryId === item.id }" @click="loadHistoryRequest(item.id)"
                        @contextmenu.prevent="handleContextMenu($event, item)">
                        <div class="history-item-name">{{ item.name || '未命名接口' }}</div>
                    </div>
                </n-scrollbar>
            </div>

            <!-- 右侧请求区域 -->
            <div class="request-tabs-section">
                <n-tabs v-model:value="activeTab" type="card" closable @close="handleCloseTab" @add="handleAddTab"
                    addable>
                    <n-tab-pane v-for="tab in tabs" :key="tab.id" :name="tab.id" :tab="tab.name">
                        <request-panel :selected-request="tab.request" @save="handleSave" />
                    </n-tab-pane>
                </n-tabs>
            </div>
        </div>

        <!-- 右键菜单 -->
        <n-dropdown :show="showDropdown" :options="dropdownOptions" :x="dropdownX" :y="dropdownY"
            placement="bottom-start" @clickoutside="showDropdown = false" @select="handleDropdownSelect" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import view from '@renderer/util/ui/ViewUtil'
import RequestPanel from './RequestPanel.vue'

// 历史记录相关
interface HistoryRequest {
    id: number
    name: string
    method: string
    url: string
    headers: Array<{ key: string, value: string }>
    queryParams: Array<{ key: string, value: string }>
    bodyType: string
    formData: any[]
    rawBody: string
    createdAt: string
}

const historyRequests = ref<HistoryRequest[]>([])
const selectedHistoryId = ref<number | null>(null)

// 加载历史记录
const loadHistory = async () => {
    try {
        historyRequests.value = await window.api.httpHistory.loadRequests()
    } catch (error) {
        view.alertErrorMessage('加载历史记录失败')
    }
}

// 计算当前选中的请求
const selectedRequest = computed(() => {
    if (!selectedHistoryId.value) return null
    return historyRequests.value.find(r => r.id === selectedHistoryId.value)
})

// 处理保存
const handleSave = async (requestData: any) => {
    try {
        let savedId: number
        if (selectedHistoryId.value) {
            requestData.id = selectedHistoryId.value
            await window.api.httpHistory.updateRequest(requestData)
            savedId = selectedHistoryId.value
            view.alertSuccessMessage('接口更新成功')
        } else {
            savedId = await window.api.httpHistory.saveRequest(requestData)
            view.alertSuccessMessage('接口保存成功')
        }

        await loadHistory()

        // 获取保存的请求数据
        const savedRequest = historyRequests.value.find(r => r.id === savedId)
        if (!savedRequest) return

        // 更新当前标签页
        const currentTabIndex = tabs.value.findIndex(tab => tab.id === activeTab.value)
        if (currentTabIndex === -1) return

        // 更新标签页信息
        tabs.value[currentTabIndex] = {
            id: `history-${savedId}`,
            name: requestData.name || '未命名接口',
            request: savedRequest
        }

        // 更新选中状态
        selectedHistoryId.value = savedId
        activeTab.value = `history-${savedId}`

    } catch (error) {
        console.error('保存历史记录失败', error)
        view.alertErrorMessage('保存历史记录失败')
    }
}

// 标签页相关
interface Tab {
    id: string
    name: string
    request: any | null
}

const tabs = ref<Tab[]>([
    { id: 'new-1', name: '新建请求', request: null }
])
const activeTab = ref('new-1')
let newTabIndex = 2

// 处理添加标签页
const handleAddTab = () => {
    const newTab = {
        id: `new-${newTabIndex}`,
        name: '新建请求',
        request: null
    }
    selectedHistoryId.value = null
    tabs.value.push(newTab)
    activeTab.value = newTab.id
    newTabIndex++
}

// 处理关闭标签页
const handleCloseTab = (name: string) => {
    const index = tabs.value.findIndex(tab => tab.id === name)
    if (index === -1) return

    tabs.value.splice(index, 1)

    // 如果关闭的是当前标签，切换到最后一个标签
    if (name === activeTab.value) {
        activeTab.value = tabs.value[tabs.value.length - 1]?.id || ''
    }

    // 如果没有标签了，创建一个新标签
    if (tabs.value.length === 0) {
        handleAddTab()
    }
}

// 加载历史请求到新标签
const loadHistoryRequest = (id: number | null) => {
    selectedHistoryId.value = id

    if (!id) return

    const request = historyRequests.value.find(r => r.id === id)
    if (!request) return

    // 创建新标签
    const newTab = {
        id: `history-${id}`,
        name: request.name || '未命名接口',
        request: request
    }

    // 检查是否已经打开
    const existingTab = tabs.value.find(tab => tab.id === newTab.id)
    if (existingTab) {
        activeTab.value = existingTab.id
        return
    }

    // 添加新标签
    tabs.value.push(newTab)
    activeTab.value = newTab.id
}

// 请求方法选项
const methodOptions = [
    { label: 'GET', value: 'GET' },
    { label: 'POST', value: 'POST' },
    { label: 'PUT', value: 'PUT' },
    { label: 'DELETE', value: 'DELETE' },
    { label: 'PATCH', value: 'PATCH' }
]

// body类型选项
const bodyTypeOptions = [
    { label: 'none', value: 'none' },
    { label: 'form-data', value: 'form-data' },
    { label: 'raw', value: 'raw' }
]

// 响应数据
const response = ref<any>(null)
const responseTime = ref<number>(0)
const loading = ref(false)

// 请求相关的响应式数据
const requestMethod = ref('GET')
const url = ref('')
const headers = ref<Array<{ key: string, value: string }>>([])
const queryParams = ref<Array<{ key: string, value: string }>>([])
const bodyType = ref('none')
const formData = ref([])
const rawBody = ref('')

// Headers 相关方法
const addHeader = () => {
    headers.value.push({ key: '', value: '' })
}

const removeHeader = (index: number) => {
    headers.value.splice(index, 1)
}

// Query params 相关方法
const addQuery = () => {
    queryParams.value.push({ key: '', value: '' })
}

const removeQuery = (index: number) => {
    queryParams.value.splice(index, 1)
}

// 发送请求
const sendRequest = async () => {
    if (!url.value) {
        view.alertErrorMessage('请输入请求地址')
        return
    }

    loading.value = true
    const startTime = Date.now()

    try {
        // 处理headers
        const headerObj = {}
        headers.value.forEach(item => {
            if (item.key) {
                headerObj[item.key] = item.value
            }
        })

        // 处理query参数
        const queryObj = {}
        queryParams.value.forEach(item => {
            if (item.key) {
                queryObj[item.key] = item.value
            }
        })

        // 处理body数据
        let data = null
        if (bodyType.value === 'form-data') {
            const formDataObj = new FormData()
            formData.value.forEach(item => {
                if (item.key) {
                    formDataObj.append(item.key, item.value)
                }
            })
            data = formDataObj
        } else if (bodyType.value === 'raw') {
            try {
                data = JSON.parse(rawBody.value)
            } catch {
                data = rawBody.value
            }
        }

        const res = await axios({
            method: requestMethod.value,
            url: url.value,
            headers: headerObj,
            params: queryObj,
            data: data
        })

        response.value = res.data
        responseTime.value = Date.now() - startTime
    } catch (error) {
        response.value = {
            error: error.message,
            ...(error.response?.data || {})
        }
    } finally {
        loading.value = false
    }
}

// 添加格式化的响应数据计算属性
const formattedResponse = computed(() => {
    if (!response.value) return ''
    try {
        return JSON.stringify(response.value, null, 2)
    } catch (e) {
        return String(response.value)
    }
})

// 添加接口名称相关的数据
const apiName = ref('')

// 右键菜单相关
const showDropdown = ref(false)
const dropdownX = ref(0)
const dropdownY = ref(0)
const currentItem = ref<HistoryRequest | null>(null)

const dropdownOptions = [
    {
        label: '克隆',
        key: 'clone'
    },
    {
        label: '删除',
        key: 'delete'
    }
]

// 处理右键菜单显示
const handleContextMenu = (e: MouseEvent, item: HistoryRequest) => {
    e.preventDefault()
    showDropdown.value = true
    dropdownX.value = e.clientX
    dropdownY.value = e.clientY
    currentItem.value = item
}

// 处理菜单项选择
const handleDropdownSelect = async (key: string) => {
    if (!currentItem.value) return

    switch (key) {
        case 'clone':
            cloneRequest(currentItem.value)
            break
        case 'delete':
            await deleteRequest(currentItem.value.id)
            break
    }
    showDropdown.value = false
}

// 克隆请求
const cloneRequest = (request: HistoryRequest) => {
    // 先清除选中状态
    selectedHistoryId.value = null

    apiName.value = `${request.name || '未命名接口'} - 副本`
    requestMethod.value = request.method
    url.value = request.url
    headers.value = JSON.parse(JSON.stringify(request.headers))
    queryParams.value = JSON.parse(JSON.stringify(request.queryParams))
    bodyType.value = request.bodyType
    formData.value = JSON.parse(JSON.stringify(request.formData || []))
    rawBody.value = request.rawBody || ''
}

// 删除请求
const deleteRequest = async (id: number) => {
    try {
        await window.api.httpHistory.deleteRequest(id)
        await loadHistory()
        view.alertSuccessMessage('删除成功')

        // 如果删除的是当前选中的请求，清空选中状态
        if (selectedHistoryId.value === id) {
            selectedHistoryId.value = null
        }

        // 删除相关的标签页
        const tabId = `history-${id}`
        const tabIndex = tabs.value.findIndex(tab => tab.id === tabId)

        if (tabIndex !== -1) {
            // 如果要删除的是当前标签，先切换到其他标签
            if (activeTab.value === tabId) {
                // 优先切换到下一个标签，如果没有下一个就切换到上一个
                const nextTab = tabs.value[tabIndex + 1] || tabs.value[tabIndex - 1]
                activeTab.value = nextTab?.id || ''
            }

            // 删除标签
            tabs.value.splice(tabIndex, 1)

            // 如果没有标签了，创建一个新标签
            if (tabs.value.length === 0) {
                handleAddTab()
            }
        }
    } catch (error) {
        console.error('删除请求失败', error)
        view.alertErrorMessage('删除失败')
    }
}

// 添加折叠相关的状态
const isCollapsed = ref(true)

// 切换折叠状态
const toggleCollapse = () => {
    isCollapsed.value = !isCollapsed.value
}

// 组件加载时获取历史记录
onMounted(() => {
    loadHistory()
})
</script>

<style scoped>
.http-container {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.content-wrapper {
    display: flex;
    gap: 16px;
    height: 100%;
    min-height: 0;
    flex: 1;
}

/* 历史记录区域样式 */
.history-section {
    width: 300px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
    transition: width 0.3s ease;
}

.history-section.collapsed {
    width: 40px;
}

.history-header {
    padding: 8px;
    border-bottom: 1px solid var(--border-color);
    background-color: var(--card-color);
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.history-header:hover {
    background-color: var(--hover-color);
}

.collapse-icon {
    transition: transform 0.3s ease;
    font-size: 12px;
    color: var(--text-color-3);
}

.collapse-icon.collapsed {
    transform: rotate(180deg);
}

/* 移除不需要的样式 */
.history-section.collapsed .history-header span {
    display: block;
}

.history-section.collapsed .history-header {
    padding: 8px;
}

/* 修改提示文字 */
.history-section.collapsed .history-header:hover::after {
    content: '展开';
    position: absolute;
    left: 100%;
    top: 50%;
    transform: translateY(-50%);
    background: var(--tooltip-color);
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    z-index: 1000;
}

.history-list {
    flex: 1;
    overflow: auto;
    min-height: 0;
}

.history-item {
    padding: 8px 16px;
    border-bottom: 1px solid var(--border-color);
    cursor: pointer;
    transition: background-color 0.2s;
    position: relative;
    user-select: none;
}

.history-item-name {
    font-size: 14px;
    color: var(--text-color-1);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.history-item-method,
.history-item-url,
.history-item-time {
    display: none;
}

.history-item:hover {
    background-color: var(--hover-color);
}

.history-item.active {
    background-color: var(--primary-color-hover);
    color: white;
}

.history-item.active .history-item-name {
    color: inherit;
}

.history-item:hover::after {
    content: '⋮';
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-color-3);
    opacity: 0.5;
}

.request-tabs-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
    border: 1px solid var(--border-color);
    border-radius: 4px;
}

.tabs-wrapper {
    position: relative;
    width: 100%;
}

:deep(.n-tabs-nav) {
    flex-shrink: 0; /* 防止导航栏被压缩 */
    padding: 4px 8px;
}

:deep(.n-tabs-nav-scroll-wrapper) {
    flex: 1;
    overflow: hidden;
}

:deep(.n-tabs-nav-scroll-content) {
    display: flex;
    align-items: center;
}

:deep(.n-tabs-wrapper) {
    flex: 1;
    overflow: hidden;
}

:deep(.n-tabs-tab) {
    padding: 0 16px;
    flex-shrink: 0;
    /* 防止标签被压缩 */
}

:deep(.n-tabs-tab-pad) {
    width: 16px;
}

:deep(.n-tabs-nav__prefix),
:deep(.n-tabs-nav__suffix) {
    flex-shrink: 0;
    /* 防止前后缀被压缩 */
}

:deep(.n-tabs-tab-wrapper) {
    flex-shrink: 0;
    /* 防止标签包装器被压缩 */
}

:deep(.n-tabs-rail) {
    flex-shrink: 0;
    /* 防止底部线条被压缩 */
}

:deep(.n-tabs-add-btn) {
    position: sticky !important;
    /* 使添加按钮保持在可见位置 */
    right: 0;
    margin-left: 8px;
    flex-shrink: 0;
    /* 防止按钮被压缩 */
    background-color: var(--card-color);
    /* 确保背景色与容器一致 */
}

:deep(.n-tab-pane) {
    height: 100%;
    overflow: auto;
    padding: 16px;
}

:deep(.n-tabs) {
    height: 100%;
    display: flex;
    flex-direction: column;
}

:deep(.n-tabs-content) {
    flex: 1;
    overflow: hidden;
    min-height: 0; /* 允许内容区域收缩 */
}
</style>